<template>
  <div class="tp-dashboard-container">
    <!-- 头部信息栏 -->
    <div class="dashboard-header">
      <el-card shadow="never" class="header-card">
        <div class="header-content">
          <!-- 左侧：实时信息 -->
          <div class="left-section">
            <div class="live-info">
              <div class="live-indicator">
                <span class="live-dot"></span>
                <span class="live-text">实时数据</span>
        </div>
              <div class="current-time">{{ currentTime }}</div>
              <div class="last-update">最后更新: {{ lastUpdateTime }}</div>
        </div>
        </div>
          
          <!-- 中间：日期选择器 -->
          <div class="center-section">
            <div class="date-picker-wrapper">
              <el-date-picker
                v-model="selectedDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                size="default"
                class="custom-date-picker"
                @change="onDateRangeChange"
              />
              <div class="quick-date-buttons">
                <el-button-group size="small">
                  <el-button @click="setQuickDate('today')" :type="quickDateType === 'today' ? 'primary' : ''">今日</el-button>
                  <el-button @click="setQuickDate('yesterday')" :type="quickDateType === 'yesterday' ? 'primary' : ''">昨日</el-button>
                  <el-button @click="setQuickDate('week')" :type="quickDateType === 'week' ? 'primary' : ''">本周</el-button>
                  <el-button @click="setQuickDate('month')" :type="quickDateType === 'month' ? 'primary' : ''">本月</el-button>
                </el-button-group>
            </div>
          </div>
          </div>
          
          <!-- 右侧：业务概览 -->
          <div class="right-section">
            <div class="business-overview">
              <div class="overview-item">
                <div class="overview-label">销售进度</div>
                <div class="overview-value">
                  <el-progress
                    type="circle"
                    :percentage="salesProgress"
                    :width="80"
                    :stroke-width="6"
                    :color="progressColors"
                  >
                    <template #default="{ percentage }">
                      <span class="progress-number">{{ percentage }}%</span>
              </template>
                  </el-progress>
              </div>
              </div>
              
              <div class="overview-item">
                <div class="overview-label">在线用户</div>
                <div class="overview-value">
                  <span class="value-number">{{ onlineUsers.toLocaleString() }}</span>
                  <div class="trend-info">
                    <el-icon class="trend-icon positive"><ArrowUp /></el-icon>
                    <span class="trend-text">+{{ onlineGrowth }}%</span>
                </div>
              </div>
              </div>
              
              <div class="overview-item">
                <div class="overview-label">店铺状态</div>
                <div class="overview-value">
                  <el-tag type="success" size="small">营业中</el-tag>
                  <div class="store-info">{{ storeCount }}家店铺</div>
                </div>
              </div>
            </div>
          </div>
              </div>
            </el-card>
                </div>

    <!-- 核心KPI指标区 -->
    <div class="kpi-section">
      <el-row :gutter="24" class="kpi-row">
        <!-- 今日GMV -->
        <el-col :span="6" :xs="24" :sm="12" :md="6">
          <div class="kpi-card primary-card">
            <div class="kpi-header">
              <div class="kpi-title">今日GMV</div>
              <el-tag type="danger" size="small" class="status-tag">实时</el-tag>
                </div>
            <div class="kpi-content">
              <div class="kpi-value">
                <span class="value-number">¥{{ formatNumber(todayGMV) }}</span>
                <div class="trend-indicator positive">
                  <el-icon><ArrowUp /></el-icon>
                  <span>+{{ gmvGrowth }}%</span>
              </div>
              </div>
              <div class="kpi-icon">
                <el-icon class="icon-money"><Money /></el-icon>
                </div>
              </div>
            <div class="kpi-footer">
              <span class="update-label">更新时间</span>
              <span class="update-time">{{ lastUpdateTime }}</span>
              </div>
                </div>
        </el-col>

        <!-- 销售目标达成率 -->
        <el-col :span="6" :xs="24" :sm="12" :md="6">
          <div class="kpi-card success-card">
            <div class="kpi-header">
              <div class="kpi-title">目标达成率</div>
              <el-tag type="success" size="small" class="status-tag">月</el-tag>
                </div>
            <div class="kpi-content">
              <div class="kpi-value">
                <span class="value-number">{{ targetAchievement }}%</span>
                <div class="trend-indicator positive">
                  <el-icon><ArrowUp /></el-icon>
                  <span>+{{ targetGrowth }}%</span>
              </div>
              </div>
              <div class="kpi-icon">
                <el-icon class="icon-target"><Trophy /></el-icon>
            </div>
            </div>
            <div class="kpi-footer">
              <span class="update-label">目标金额</span>
              <span class="update-time">¥{{ formatNumber(monthlyTarget) }}</span>
          </div>
          </div>
      </el-col>

        <!-- 今日订单量 -->
        <el-col :span="6" :xs="24" :sm="12" :md="6">
          <div class="kpi-card warning-card">
            <div class="kpi-header">
              <div class="kpi-title">今日订单量</div>
              <el-tag type="warning" size="small" class="status-tag">日</el-tag>
                </div>
            <div class="kpi-content">
              <div class="kpi-value">
                <span class="value-number">{{ formatNumber(todayOrders) }}</span>
                <div class="trend-indicator positive">
                  <el-icon><ArrowUp /></el-icon>
                  <span>+{{ ordersGrowth }}%</span>
              </div>
              </div>
              <div class="kpi-icon">
                <el-icon class="icon-order"><ShoppingCart /></el-icon>
                </div>
                </div>
            <div class="kpi-footer">
              <span class="update-label">昨日订单</span>
              <span class="update-time">{{ formatNumber(yesterdayOrders) }}</span>
              </div>
              </div>
      </el-col>

        <!-- 转化率 -->
        <el-col :span="6" :xs="24" :sm="12" :md="6">
          <div class="kpi-card info-card">
            <div class="kpi-header">
              <div class="kpi-title">转化率</div>
              <el-tag type="info" size="small" class="status-tag">日</el-tag>
                </div>
            <div class="kpi-content">
              <div class="kpi-value">
                <span class="value-number">{{ conversionRate }}%</span>
                <div class="trend-indicator negative">
                  <el-icon><ArrowDown /></el-icon>
                  <span>{{ conversionChange }}%</span>
              </div>
              </div>
              <div class="kpi-icon">
                <el-icon class="icon-conversion"><DataAnalysis /></el-icon>
                </div>
                </div>
            <div class="kpi-footer">
              <span class="update-label">平均转化率</span>
              <span class="update-time">{{ avgConversionRate }}%</span>
              </div>
              </div>
      </el-col>
      </el-row>
                </div>

    <!-- 详细指标区 -->
    <div class="metrics-section">
      <el-row :gutter="16" class="metrics-row">
        <!-- 客单价 -->
        <el-col :span="4" :xs="12" :sm="8" :md="4">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">客单价</span>
              </div>
            <div class="metric-content">
              <div class="metric-value">¥{{ unitPrice }}</div>
              <div class="metric-trend positive">
                <el-icon><Top /></el-icon>
                <span>+{{ unitPriceGrowth }}%</span>
              </div>
                </div>
          </div>
        </el-col>

        <!-- 访客数 -->
        <el-col :span="4" :xs="12" :sm="8" :md="4">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">访客数</span>
                </div>
            <div class="metric-content">
              <div class="metric-value">{{ formatNumber(visitors) }}</div>
              <div class="metric-trend positive">
                <el-icon><Top /></el-icon>
                <span>+{{ visitorsGrowth }}%</span>
              </div>
              </div>
          </div>
      </el-col>

        <!-- 成交用户数 -->
        <el-col :span="4" :xs="12" :sm="8" :md="4">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">成交用户</span>
                </div>
            <div class="metric-content">
              <div class="metric-value">{{ formatNumber(buyers) }}</div>
              <div class="metric-trend positive">
                <el-icon><Top /></el-icon>
                <span>+{{ buyersGrowth }}%</span>
              </div>
              </div>
                </div>
        </el-col>

        <!-- 商品浏览量 -->
        <el-col :span="4" :xs="12" :sm="8" :md="4">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">商品浏览</span>
                </div>
            <div class="metric-content">
              <div class="metric-value">{{ formatNumber(productViews) }}K</div>
              <div class="metric-trend positive">
                <el-icon><Top /></el-icon>
                <span>+{{ productViewsGrowth }}%</span>
              </div>
              </div>
          </div>
      </el-col>

        <!-- 店铺关注数 -->
        <el-col :span="4" :xs="12" :sm="8" :md="4">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">店铺关注</span>
                </div>
            <div class="metric-content">
              <div class="metric-value">{{ formatNumber(storeFollows) }}</div>
              <div class="metric-trend positive">
                <el-icon><Top /></el-icon>
                <span>+{{ storeFollowsGrowth }}%</span>
              </div>
              </div>
                </div>
        </el-col>

        <!-- 退款率 -->
        <el-col :span="4" :xs="12" :sm="8" :md="4">
          <div class="metric-card">
            <div class="metric-header">
              <span class="metric-title">退款率</span>
                </div>
            <div class="metric-content">
              <div class="metric-value">{{ refundRate }}%</div>
              <div class="metric-trend negative">
                <el-icon><Bottom /></el-icon>
                <span>{{ refundRateChange }}%</span>
              </div>
              </div>
          </div>
      </el-col>
    </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="24" class="charts-row">
        <!-- 销售趋势图 -->
        <el-col :span="16" :xs="24" :sm="24" :md="16">
          <el-card shadow="never" class="chart-card">
          <template #header>
              <div class="chart-header">
                <div class="chart-title">销售趋势</div>
                <div class="chart-controls">
                  <el-radio-group v-model="selectedTimeRange" size="small" class="date-selector" @change="onTimeRangeChange">
                <el-radio-button :value="7">近7天</el-radio-button>
                <el-radio-button :value="30">近30天</el-radio-button>
                    <el-radio-button :value="90">近3个月</el-radio-button>
              </el-radio-group>
                </div>
            </div>
          </template>
            <div class="chart-content">
              <ECharts :options="trendChartOptions" height="400px" />
            </div>
        </el-card>
      </el-col>

        <!-- 品类销售占比 -->
        <el-col :span="8" :xs="24" :sm="24" :md="8">
          <el-card shadow="never" class="chart-card category-chart-card">
            <template #header>
              <div class="chart-header">
                <div class="chart-title">品类销售占比</div>
              </div>
            </template>
            <div class="chart-content category-chart-content">
              <!-- 饼图容器 -->
              <div class="pie-chart-container">
                <ECharts :options="categoryChartOptions" height="320px" />
              </div>
              
              <!-- 图例容器 -->
              <div class="category-legend-container">
                <div class="legend-title">品类明细</div>
                <div class="legend-list">
                  <div 
                    v-for="(item, index) in displayLegendData" 
                    :key="index"
                    class="legend-item"
                  >
                    <div class="legend-color" :style="{ backgroundColor: item.color }"></div>
                    <div class="legend-info">
                      <div class="legend-name">{{ item.name }}</div>
                      <div class="legend-value">
                        <span class="percentage">{{ item.percentage }}%</span>
                        <span class="amount">¥{{ item.amount }}万</span>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 显示"其他"项，当品类超过10个时 -->
                  <div v-if="otherCategoriesData" class="legend-item other-item">
                    <div class="legend-color" style="background-color: #e6e6e6"></div>
                    <div class="legend-info">
                      <div class="legend-name">其他 ({{ otherCategoriesData.count }}项)</div>
                      <div class="legend-value">
                        <span class="percentage">{{ otherCategoriesData.percentage }}%</span>
                        <span class="amount">¥{{ otherCategoriesData.amount }}万</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 总计信息 -->
                <div class="legend-total" v-if="categoryTotalData">
                  <div class="total-label">总计</div>
                  <div class="total-amount">¥{{ categoryTotalData.totalAmount }}万</div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
    </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { dayjs } from "element-plus"
import { 
  ArrowUp, 
  ArrowDown, 
  Money, 
  Trophy, 
  ShoppingCart, 
  DataAnalysis,
  Top,
  Bottom
} from "@element-plus/icons-vue"
import TPDashboardAPI from "@/api/dashboard/tp.api"
import * as echarts from 'echarts'

defineOptions({
  name: "TPDashboard",
  inheritAttrs: false,
})

// 时间相关
const currentDate = new Date()
const month = currentDate.getMonth() + 1
const currentDay = dayjs().format('YYYY-MM-DD HH:mm:ss')

// 获取本月天数
const totalDaysInMonth = computed(() => {
  return new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate()
})

// 获取当前是本月的第几天
const currentDayOfMonth = computed(() => {
  return new Date().getDate()
})

// 时间进度计算
const progressRef = ref(0)
const updateProgress = () => {
  const now = new Date()
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
  const startOfNextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1)
  const totalMonthTime = startOfNextMonth.getTime() - startOfMonth.getTime()
  const elapsedTime = now.getTime() - startOfMonth.getTime()
  progressRef.value = (elapsedTime / totalMonthTime) * 100
}

const currentProgress = computed(() => {
  return Math.min(Math.max(progressRef.value, 0), 100)
})

const currentProgressValue = computed(() => 
  parseFloat(currentProgress.value.toFixed(1))
)

const progressColor = computed(() => {
  if (currentProgressValue.value < 30) return '#E6A23C'
  if (currentProgressValue.value < 70) return '#409EFF'
  return '#67C23A'
})

// 格式化函数
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const formatTime = (time: string) => {
  return dayjs(time).format('HH:mm')
}

// 图表配置
const selectedTimeRange = ref(7)
const trendChartOptions = ref({})

// 图表数据 - 需要在updateTrendChartOptions之前定义
const chartData = ref({
  7: {
    dates: ['06-01', '06-02', '06-03', '06-04', '06-05', '06-06', '06-07'],
    gmv: [25, 28, 31, 29, 33, 35, 42],
    orders: [1100, 1200, 1350, 1280, 1450, 1520, 1800]
  },
  30: {
    dates: Array.from({length: 30}, (_, i) => {
      const date = new Date()
      date.setDate(date.getDate() - 29 + i)
      return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }),
    gmv: Array.from({length: 30}, () => Math.floor(Math.random() * 20) + 25),
    orders: Array.from({length: 30}, () => Math.floor(Math.random() * 500) + 1000)
  },
  90: {
    dates: Array.from({length: 12}, (_, i) => {
      const date = new Date()
      date.setDate(date.getDate() - (12 - i) * 7)
      return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }),
    gmv: Array.from({length: 12}, () => Math.floor(Math.random() * 30) + 20),
    orders: Array.from({length: 12}, () => Math.floor(Math.random() * 800) + 800)
  }
})

const categoryChartOptions = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c}%'
  },
  graphic: [
    {
      type: 'text',
      left: 'center',
      top: '45%',
      style: {
        text: '品类占比',
        textAlign: 'center',
        textVerticalAlign: 'middle',
        fill: '#303133',
        fontSize: 13,
        fontWeight: 'bold'
      },
      z: 100
    },
    {
      type: 'text',
      left: 'center',
      top: '55%',
      style: {
        text: '暂无数据',
        textAlign: 'center',
        textVerticalAlign: 'middle',
        fill: '#409EFF',
        fontSize: 12,
        fontWeight: 'normal'
      },
      z: 100
    }
  ],
  series: [
    {
      name: '品类销售',
      type: 'pie',
      radius: ['50%', '75%'],
      center: ['50%', '50%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: false
      },
      labelLine: {
        show: false
      }
    }
  ]
} as any)

// 访问趋势图表配置
const updateTrendChartOptions = () => {
  const data = chartData.value[selectedTimeRange.value as keyof typeof chartData.value]
  
  trendChartOptions.value = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#e6e6e6',
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      data: ['GMV(万元)', '订单量'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates,
      axisLine: {
        lineStyle: {
          color: '#e6e6e6'
        }
      },
      axisLabel: {
        color: '#666'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: 'GMV(万元)',
        position: 'left',
        axisLine: {
          lineStyle: {
            color: '#e6e6e6'
          }
        },
        axisLabel: {
          color: '#666'
        },
        splitLine: {
        lineStyle: {
            color: '#f5f5f5'
          }
        }
      },
      {
        type: 'value',
        name: '订单量',
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#e6e6e6'
          }
        },
        axisLabel: {
          color: '#666'
        }
      }
    ],
    series: [
      {
        name: 'GMV(万元)',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#4CAF50'
        },
        itemStyle: {
          color: '#4CAF50'
        },
        data: data.gmv
      },
      {
        name: '订单量',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        lineStyle: {
          width: 3,
          color: '#2196F3'
        },
        itemStyle: {
          color: '#2196F3'
        },
        data: data.orders
      }
    ]
  }
}

// 初始化
updateProgress()
const timer = setInterval(updateProgress, 60000) // 每分钟更新一次

// 监听图表时间范围变化
watch(selectedTimeRange, () => {
  updateTrendChartOptions()
}, { immediate: true })

onMounted(() => {
  updateTrendChartOptions()
  loadDashboardData()
})

onUnmounted(() => {
  if (timeInterval.value) {
    clearInterval(timeInterval.value)
  }
  window.removeEventListener('resize', resizeCharts)
})

// 响应式数据
const currentTime = ref('')
const lastUpdateTime = ref('')
const timeInterval = ref<NodeJS.Timeout | null>(null)

// 模拟数据
const todayGMV = ref(256800)
const gmvGrowth = ref(12.5)
const targetAchievement = ref(68.2)
const targetGrowth = ref(5.3)
const monthlyTarget = ref(2500000)
const todayOrders = ref(1234)
const ordersGrowth = ref(8.7)
const yesterdayOrders = ref(1135)
const conversionRate = ref(3.52)
const conversionChange = ref(-0.8)
const avgConversionRate = ref(3.68)

const unitPrice = ref(208)
const unitPriceGrowth = ref(5.2)
const visitors = ref(35042)
const visitorsGrowth = ref(12.3)
const buyers = ref(1234)
const buyersGrowth = ref(8.7)
const productViews = ref(156.8)
const productViewsGrowth = ref(15.6)
const storeFollows = ref(2456)
const storeFollowsGrowth = ref(23.1)
const refundRate = ref(2.1)
const refundRateChange = ref(-0.3)

// 计算属性
const timeProgress = ref(12.6)
const progressCircumference = ref(2 * Math.PI * 35)
const progressOffset = ref((1 - timeProgress.value / 100) * progressCircumference.value)

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
  
  lastUpdateTime.value = now.toLocaleString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
  
  // 更新时间进度
  const hours = now.getHours()
  const minutes = now.getMinutes()
  const seconds = now.getSeconds()
  const totalSeconds = hours * 3600 + minutes * 60 + seconds
  const daySeconds = 24 * 3600
  const progressValue = ((totalSeconds / daySeconds) * 100).toFixed(1)
  timeProgress.value = parseFloat(progressValue)
  progressOffset.value = (1 - timeProgress.value / 100) * progressCircumference.value
}

// 时间范围切换
const onTimeRangeChange = (value: string | number | boolean | undefined) => {
  if (typeof value === 'number') {
    selectedTimeRange.value = value
    updateTrendChartOptions()
  }
}

// 初始化趋势图
const initTrendChart = () => {
  updateTrendChartOptions()
}

// 初始化饼图
const initCategoryChart = () => {
  // 饼图配置已在reactive中定义
}

// 窗口大小改变时重新渲染图表
const resizeCharts = () => {
  // 图表重新渲染逻辑由ECharts组件自动处理
}

// 头部卡片相关数据
const selectedDateRange = ref<[string, string]>([
  dayjs().format('YYYY-MM-DD'),
  dayjs().format('YYYY-MM-DD')
])
const quickDateType = ref('today')

// 业务数据
const salesProgress = ref(68.2)
const onlineUsers = ref(1456)
const onlineGrowth = ref(8.3)
const storeCount = ref(12)

// 品类图例相关数据
const displayLegendData = ref<any[]>([])
const otherCategoriesData = ref<any>(null)
const categoryTotalData = ref<any>(null)

// 进度条颜色配置
const progressColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]

// 日期相关方法
const onDateRangeChange = (dates: [string, string] | null) => {
  if (dates) {
    selectedDateRange.value = dates
    quickDateType.value = ''
    console.log('选择日期范围:', dates)
    // 这里可以添加数据刷新逻辑
    refreshDashboardData()
  }
}

const setQuickDate = (type: string) => {
  quickDateType.value = type
  const now = dayjs()
  
  switch (type) {
    case 'today':
      selectedDateRange.value = [now.format('YYYY-MM-DD'), now.format('YYYY-MM-DD')]
      break
    case 'yesterday':
      const yesterday = now.subtract(1, 'day')
      selectedDateRange.value = [yesterday.format('YYYY-MM-DD'), yesterday.format('YYYY-MM-DD')]
      break
    case 'week':
      const startOfWeek = now.startOf('week')
      selectedDateRange.value = [startOfWeek.format('YYYY-MM-DD'), now.format('YYYY-MM-DD')]
      break
    case 'month':
      const startOfMonth = now.startOf('month')
      selectedDateRange.value = [startOfMonth.format('YYYY-MM-DD'), now.format('YYYY-MM-DD')]
      break
  }
  
  console.log('快速选择日期:', type, selectedDateRange.value)
  refreshDashboardData()
}

// 加载看板数据
const loadDashboardData = async () => {
  try {
    const params = {
      startDate: selectedDateRange.value[0],
      endDate: selectedDateRange.value[1]
    }
    
    // 获取所有数据
    const result = await TPDashboardAPI.getAllData(params)
    
    // 更新头部信息
    if (result.headerInfo) {
      onlineUsers.value = result.headerInfo.onlineUsers
      onlineGrowth.value = result.headerInfo.onlineGrowth
      salesProgress.value = result.headerInfo.salesProgress
      storeCount.value = result.headerInfo.storeCount
    }
    
    // 更新KPI指标
    if (result.kpiMetrics) {
      todayGMV.value = result.kpiMetrics.todayGMV
      gmvGrowth.value = result.kpiMetrics.gmvGrowth
      targetAchievement.value = result.kpiMetrics.targetAchievement
      targetGrowth.value = result.kpiMetrics.targetGrowth
      monthlyTarget.value = result.kpiMetrics.monthlyTarget
      todayOrders.value = result.kpiMetrics.todayOrders
      yesterdayOrders.value = result.kpiMetrics.yesterdayOrders
      ordersGrowth.value = result.kpiMetrics.ordersGrowth
      conversionRate.value = result.kpiMetrics.conversionRate
      conversionChange.value = result.kpiMetrics.conversionChange
      avgConversionRate.value = result.kpiMetrics.avgConversionRate
    }
    
    // 更新详细指标
    if (result.detailMetrics) {
      unitPrice.value = result.detailMetrics.unitPrice
      unitPriceGrowth.value = result.detailMetrics.unitPriceGrowth
      visitors.value = result.detailMetrics.visitors
      visitorsGrowth.value = result.detailMetrics.visitorsGrowth
      buyers.value = result.detailMetrics.buyers
      buyersGrowth.value = result.detailMetrics.buyersGrowth
      productViews.value = result.detailMetrics.productViews
      productViewsGrowth.value = result.detailMetrics.productViewsGrowth
      storeFollows.value = result.detailMetrics.storeFollows
      storeFollowsGrowth.value = result.detailMetrics.storeFollowsGrowth
      refundRate.value = result.detailMetrics.refundRate
      refundRateChange.value = result.detailMetrics.refundRateChange
    }
    
    // 更新品类销售数据
    if (result.categorySales) {
      updateCategoryChart(result.categorySales)
    }
    
    console.log('看板数据加载成功', result)
  } catch (error) {
    console.error('看板数据加载失败，使用模拟数据:', error)
    // 保持现有的模拟数据不变
  }
}

// 更新品类销售饼图
const updateCategoryChart = (categoryData: any) => {
  if (!categoryData || !categoryData.data || categoryData.data.length === 0) {
    // 空数据时显示提示
    categoryChartOptions.value = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}%'
      },
      graphic: [
        {
          type: 'text',
          left: 'center',
          top: '45%',
          style: {
            text: '品类占比',
            textAlign: 'center',
            textVerticalAlign: 'middle',
            fill: '#303133',
            fontSize: 13,
            fontWeight: 'bold'
          },
          z: 100
        },
        {
          type: 'text',
          left: 'center',
          top: '55%',
          style: {
            text: '暂无数据',
            textAlign: 'center',
            textVerticalAlign: 'middle',
            fill: '#909399',
            fontSize: 12,
            fontWeight: 'normal'
          },
          z: 100
        }
      ],
      series: [
        {
          name: '品类销售',
          type: 'pie',
          radius: ['35%', '65%'],
          center: ['50%', '50%'],
          data: [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: false
          },
          labelLine: {
            show: false
          }
        }
      ]
    }
    
    // 清空图例数据
    displayLegendData.value = []
    otherCategoriesData.value = null
    categoryTotalData.value = null
    return
  }
  
  // 按金额降序排序
  const sortedData = [...categoryData.data].sort((a, b) => b.amount - a.amount)
  
  // 取前9个品类，其余合并为"其他"
  const maxDisplayCategories = 9
  const topCategories = sortedData.slice(0, maxDisplayCategories)
  const otherCategories = sortedData.slice(maxDisplayCategories)
  
  // 处理图例数据
  displayLegendData.value = topCategories.map((item: any) => ({
    name: item.name,
    color: item.color,
    percentage: item.percentage,
    amount: (item.amount / 10000).toFixed(1)
  }))
  
  // 处理"其他"分类
  if (otherCategories.length > 0) {
    const otherTotalAmount = otherCategories.reduce((sum, item) => sum + item.amount, 0)
    const otherTotalPercentage = otherCategories.reduce((sum, item) => sum + item.percentage, 0)
    
    otherCategoriesData.value = {
      count: otherCategories.length,
      percentage: otherTotalPercentage.toFixed(1),
      amount: (otherTotalAmount / 10000).toFixed(1)
    }
  } else {
    otherCategoriesData.value = null
  }
  
  // 设置总计数据
  categoryTotalData.value = {
    totalAmount: (categoryData.summary.totalAmount / 10000).toFixed(1)
  }
  
  // 准备饼图数据
  const pieData = topCategories.map((item: any) => ({
    value: item.percentage,
    name: item.name,
    itemStyle: { color: item.color }
  }))
  
  // 如果有"其他"分类，添加到饼图数据
  if (otherCategories.length > 0) {
    const otherTotalPercentage = otherCategories.reduce((sum, item) => sum + item.percentage, 0)
    pieData.push({
      value: otherTotalPercentage,
      name: '其他',
      itemStyle: { color: '#e6e6e6' }
    })
  }
  
  // 更新饼图配置
  (categoryChartOptions.value as any) = {
    tooltip: {
      trigger: 'item' as const,
      formatter: (params: any) => {
        if (params.name === '其他') {
          return `${params.seriesName} <br/>${params.name} (${otherCategories.length}项): ${params.percent}%`
        }
        return `${params.seriesName} <br/>${params.name}: ${params.percent}%`
      }
    } as any,
    graphic: [
      {
        type: 'text',
        left: 'center',
        top: '45%',
        style: {
          text: '品类总金额',
          textAlign: 'center',
          textVerticalAlign: 'middle',
          fill: '#303133',
          fontSize: 13,
          fontWeight: 'bold'
        },
        z: 100
      },
      {
        type: 'text',
        left: 'center',
        top: '55%',
        style: {
          text: '¥' + (categoryData.summary.totalAmount / 10000).toFixed(1) + '万',
          textAlign: 'center',
          textVerticalAlign: 'middle',
          fill: '#409EFF',
          fontSize: 14,
          fontWeight: 'bold'
        },
        z: 100
      }
    ],
    series: [
      {
        name: '品类销售',
        type: 'pie',
        radius: ['35%', '65%'],
        center: ['50%', '50%'],
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        }
      }
    ]
  }
}

// 刷新看板数据
const refreshDashboardData = () => {
  console.log('刷新数据，日期范围:', selectedDateRange.value)
  loadDashboardData()
}

onMounted(async () => {
  // 初始化时间
  updateTime()
  timeInterval.value = setInterval(updateTime, 1000)
  
  // 等待DOM更新后初始化图表
  await nextTick()
  initTrendChart()
  initCategoryChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts)
})
</script>

<style lang="scss" scoped>
.tp-dashboard-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;

  .dashboard-header {
    margin-bottom: 24px;
    
    .header-card {
      border-radius: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      
      .header-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 0;
        gap: 24px;
        
        .left-section, .right-section {
          flex: 1;
          min-width: 0;
        }
        
        .center-section {
          flex: 2;
          display: flex;
          justify-content: center;
        }
        
        .left-section {
          .live-info {
            .live-indicator {
              display: flex;
              align-items: center;
              margin-bottom: 8px;
              
              .live-dot {
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background-color: #67C23A;
                margin-right: 6px;
                animation: pulse 2s infinite;
              }
              
              .live-text {
                font-size: 14px;
                color: #67C23A;
                font-weight: 500;
              }
            }
            
            .current-time {
              font-size: 20px;
              font-weight: 600;
              color: #303133;
              margin-bottom: 4px;
            }
            
            .last-update {
              font-size: 12px;
              color: #909399;
            }
          }
        }
        
        .center-section {
          .date-picker-wrapper {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 12px;
            
            .custom-date-picker {
              --el-date-editor-width: 280px;
            }
            
            .quick-date-buttons {
              .el-button-group {
                .el-button {
                  --el-button-bg-color: #f5f7fa;
                  --el-button-text-color: #606266;
                  --el-button-hover-bg-color: #409EFF;
                  --el-button-hover-text-color: #fff;
                }
              }
            }
          }
        }
        
        .right-section {
          .business-overview {
            display: flex;
            flex-direction: column;
            gap: 16px;
            
            .overview-item {
              display: flex;
              align-items: center;
              justify-content: space-between;
              
              .overview-label {
                font-size: 14px;
                color: #909399;
                font-weight: 500;
                min-width: 70px;
              }
              
              .overview-value {
                display: flex;
                align-items: center;
                gap: 12px;
                
                .progress-number {
                  font-size: 14px;
                  font-weight: 600;
                  color: #303133;
                }
                
                .value-number {
                  font-size: 20px;
                  font-weight: 600;
                  color: #303133;
                }
                
                .trend-info {
                  display: flex;
                  align-items: center;
                  
                  .trend-icon {
                    font-size: 14px;
                    margin-right: 2px;
                    
                    &.positive {
                      color: #67C23A;
                    }
                  }
                  
                  .trend-text {
                    font-size: 12px;
                    color: #67C23A;
                    font-weight: 500;
                  }
                }
                
                .store-info {
                  font-size: 12px;
                  color: #909399;
                  margin-top: 2px;
                }
              }
            }
          }
        }
      }
    }
  }

  .kpi-section {
    margin-bottom: 24px;
    
    .kpi-row {
      .kpi-card {
        background: #fff;
        border-radius: 12px;
        padding: 20px;
        min-height: 140px;
        height: auto;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        border-left: 4px solid;
        transition: all 0.3s ease;
        cursor: pointer;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }
        
        &.primary-card {
          border-left-color: #409EFF;
          
          .icon-money {
            color: #409EFF;
          }
        }
        
        &.success-card {
          border-left-color: #67C23A;
          
          .icon-target {
            color: #67C23A;
          }
        }
        
        &.warning-card {
          border-left-color: #E6A23C;
          
          .icon-order {
            color: #E6A23C;
          }
        }
        
        &.info-card {
          border-left-color: #909399;
          
          .icon-conversion {
            color: #909399;
          }
        }
        
        .kpi-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
    margin-bottom: 12px;
          flex-shrink: 0;
          
          .kpi-title {
            font-size: 14px;
            color: #606266;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .status-tag {
            font-size: 11px;
            flex-shrink: 0;
          }
        }
        
        .kpi-content {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 12px;
          flex: 1;
          
          .kpi-value {
            flex: 1;
            min-width: 0;
            
            .value-number {
              font-size: 24px;
              font-weight: 700;
              color: #303133;
              display: block;
              line-height: 1.1;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .trend-indicator {
              display: flex;
              align-items: center;
              margin-top: 2px;
              font-size: 11px;
              
              &.positive {
                color: #67C23A;
              }
              
              &.negative {
                color: #F56C6C;
              }
              
              .el-icon {
                margin-right: 2px;
                font-size: 12px;
              }
            }
          }
          
          .kpi-icon {
            flex-shrink: 0;
            margin-left: 8px;
            
            .el-icon {
              font-size: 36px;
              opacity: 0.8;
            }
          }
        }
        
        .kpi-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 11px;
          color: #909399;
          flex-shrink: 0;
          
          .update-label,
          .update-time {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .update-time {
            max-width: 60px;
          }
        }
      }
    }
  }

  .metrics-section {
    margin-bottom: 24px;
    
    .metrics-row {
      .metric-card {
        background: #fff;
        border-radius: 8px;
        padding: 16px;
        height: 80px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        
    &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .metric-header {
          margin-bottom: 8px;
          
          .metric-title {
            font-size: 14px;
            color: #909399;
          }
        }
        
        .metric-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .metric-value {
            font-size: 20px;
            font-weight: 600;
            color: #303133;
          }
          
          .metric-trend {
            display: flex;
            align-items: center;
            font-size: 12px;
            
            &.positive {
              color: #67C23A;
            }
            
            &.negative {
              color: #F56C6C;
            }
            
            .el-icon {
              margin-right: 2px;
            }
          }
        }
      }
    }
  }

  .charts-section {
    .charts-row {
      .chart-card {
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .chart-title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
          }
          
          .chart-controls {
            .date-selector {
              .el-radio-button {
                --el-radio-button-checked-bg-color: #409EFF;
                --el-radio-button-checked-text-color: #fff;
              }
            }
          }
        }
        
        .chart-content {
          margin-top: 16px;
        }
        
        // 品类图表特殊样式
        &.category-chart-card {
          .category-chart-content {
            display: flex;
            flex-direction: column;
            gap: 16px;
            
            .pie-chart-container {
              flex-shrink: 0;
            }
            
            .category-legend-container {
              border-top: 1px solid #f0f0f0;
              padding-top: 16px;
              
              .legend-title {
                font-size: 14px;
                font-weight: 600;
                color: #303133;
                margin-bottom: 12px;
                text-align: center;
              }
              
              .legend-list {
                max-height: 200px;
                overflow-y: auto;
                padding-right: 4px;
                
                &::-webkit-scrollbar {
                  width: 4px;
                }
                
                &::-webkit-scrollbar-track {
                  background: #f1f1f1;
                  border-radius: 2px;
                }
                
                &::-webkit-scrollbar-thumb {
                  background: #c1c1c1;
                  border-radius: 2px;
                  
                  &:hover {
                    background: #a1a1a1;
                  }
                }
                
                .legend-item {
                  display: flex;
                  align-items: center;
                  padding: 6px 0;
                  border-bottom: 1px solid #f8f8f8;
                  
                  &:last-child {
                    border-bottom: none;
                  }
                  
                  &.other-item {
                    border-top: 1px solid #e6e6e6;
                    margin-top: 4px;
                    padding-top: 10px;
                    background-color: #fafafa;
                    margin-left: -8px;
                    margin-right: -8px;
                    padding-left: 8px;
                    padding-right: 8px;
                    border-radius: 4px;
                  }
                  
                  .legend-color {
                    width: 12px;
                    height: 12px;
                    border-radius: 2px;
                    margin-right: 8px;
                    flex-shrink: 0;
                  }
                  
                  .legend-info {
                    flex: 1;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    min-width: 0;
                    
                    .legend-name {
                      font-size: 13px;
                      color: #303133;
                      font-weight: 500;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      max-width: 100px;
                    }
                    
                    .legend-value {
                      display: flex;
                      flex-direction: column;
                      align-items: flex-end;
                      
                      .percentage {
                        font-size: 14px;
                        font-weight: 600;
                        color: #409EFF;
                      }
                      
                      .amount {
                        font-size: 12px;
                        color: #909399;
                        margin-top: 1px;
                      }
                    }
                  }
                }
              }
              
              .legend-total {
                border-top: 2px solid #409EFF;
                margin-top: 12px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                padding: 12px 16px;
                border-radius: 6px;
                margin-left: -8px;
                margin-right: -8px;
                
                .total-label {
                  font-size: 14px;
                  font-weight: 600;
                  color: #303133;
                }
                
                .total-amount {
                  font-size: 16px;
                  font-weight: 700;
                  color: #409EFF;
                }
              }
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .tp-dashboard-container {
    padding: 16px;
    
    .dashboard-header .header-card .header-content {
      flex-direction: column;
      gap: 20px;
      padding: 12px 0;
      
      .left-section, .center-section, .right-section {
        width: 100%;
        flex: none;
      }
      
      .center-section {
        .date-picker-wrapper {
          .custom-date-picker {
            --el-date-editor-width: 240px;
          }
          
          .quick-date-buttons {
            .el-button-group {
              .el-button {
                font-size: 12px;
                padding: 6px 12px;
              }
            }
          }
        }
      }
      
      .right-section {
        .business-overview {
          flex-direction: row;
          justify-content: space-around;
          
          .overview-item {
            flex-direction: column;
            text-align: center;
            
            .overview-label {
              margin-bottom: 4px;
              min-width: auto;
            }
          }
        }
      }
    }
    
    .kpi-section .kpi-row .kpi-card {
      margin-bottom: 16px;
      min-height: 120px;
      padding: 16px;
      
      .kpi-content {
        .kpi-value {
          .value-number {
            font-size: 20px;
          }
        }
        
        .kpi-icon {
          .el-icon {
            font-size: 28px;
          }
        }
      }
      
      .kpi-footer {
        font-size: 10px;
        
        .update-time {
          max-width: 50px;
        }
      }
    }
    
    .metrics-section .metrics-row .metric-card {
      margin-bottom: 12px;
    }
    
    .charts-section .charts-row .chart-card {
      margin-bottom: 16px;
      
      .chart-header {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start;
        
        .chart-controls {
          .date-selector {
            .el-radio-button__inner {
              font-size: 12px;
              padding: 8px 12px;
            }
          }
        }
      }
      
      // 品类图表移动端样式
      &.category-chart-card {
        .category-chart-content {
          .category-legend-container {
            .legend-list {
              max-height: 150px;
              
              .legend-item {
                .legend-info {
                  .legend-name {
                    max-width: 60px;
                    font-size: 12px;
                  }
                  
                  .legend-value {
                    .percentage {
                      font-size: 13px;
                    }
                    
                    .amount {
                      font-size: 11px;
                    }
                  }
                }
              }
            }
            
            .legend-total {
              .total-label {
                font-size: 13px;
              }
              
              .total-amount {
                font-size: 15px;
              }
            }
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .tp-dashboard-container {
    padding: 12px;
    
    .dashboard-header .header-card .header-content {
      .center-section {
        .date-picker-wrapper {
          .custom-date-picker {
            --el-date-editor-width: 200px;
          }
          
          .quick-date-buttons {
            .el-button-group {
              .el-button {
                font-size: 11px;
                padding: 4px 8px;
              }
            }
          }
        }
      }
      
      .right-section {
        .business-overview {
          .overview-item {
            .overview-value {
              gap: 8px;
              
              .value-number {
                font-size: 16px;
              }
            }
          }
        }
      }
    }
    
    .kpi-section .kpi-row .kpi-card {
      padding: 12px;
      min-height: 100px;
      
      .kpi-header {
        margin-bottom: 8px;
        
        .kpi-title {
      font-size: 13px;
        }
        
        .status-tag {
          font-size: 10px;
        }
      }
      
      .kpi-content {
        margin-bottom: 8px;
        
        .kpi-value {
          .value-number {
            font-size: 18px;
          }
          
          .trend-indicator {
            font-size: 10px;
          }
        }
        
        .kpi-icon {
          margin-left: 4px;
          
          .el-icon {
            font-size: 24px;
          }
        }
      }
      
      .kpi-footer {
        font-size: 9px;
      }
    }
  }
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>
